//
//  MineFollowListViewController.m
//  ShowYork
//
//  Created by hxh on 2020/10/13.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "MineFansListViewController.h"
#import "MineFollowListCell.h"
#import "MineFollowItemModel.h"
#import "UserInfoFollowModel.h"

@interface MineFansListViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,MineFollowListCellDelegate>
@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDataLb;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSNumber *userId;
@property (nonatomic,copy)NSString *userName;

@end

@implementation MineFansListViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;

}

- (instancetype)initWithUserInfoId:(NSNumber *)userId{
    if (self = [super init]) {
        self.userId = userId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    
    [self setUI];
    
    [self registNote];
   
}

- (void)setUI{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
        
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noData_tag"]];
    self.noDataImgView.hidden = YES;
    [self.view addSubview:self.noDataImgView];
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-44);
    }];
   
    
    self.noDataLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    self.noDataLb.text = @"无内容";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    self.noDataLb.textAlignment = NSTextAlignmentCenter;
    self.noDataLb.hidden = YES;
    [self.view addSubview:self.noDataLb];
    
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(6);
        make.centerX.equalTo(self.view);
    }];
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadFansListSource];
    }];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadFansListSource];
    }];
    
  
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFanItemStatus:) name:@"updateUserInfoFollowListStatus" object:nil];
}

- (void)updateFanItemStatus:(NSNotification *)note{
    MineFollowItemModel *item = note.userInfo[@"data"];
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(MineFollowItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([item.userId isEqualToNumber:obj.userId]) {
            index = idx;
            obj.followCode = item.followCode;
            *stop = YES;
        }
    }];
    if (index != -1) {
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)loadFansListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = self.userId;
    param[@"md5"] = [RPAppManager md5StrWithApi:UserFans];
    param[@"pageSize"] = @(10);
    param[@"pageIndex"] = @(self.page);
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(UserFans) parames:param success:^(id responseObj) {
        if (self.page == 1) {
            self.dataArray = [MineFollowItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[MineFollowItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
    
        [self stopRefreshing];
        
        self.noDataImgView.hidden = self.dataArray.count > 0;
        self.noDataLb.hidden = self.dataArray.count > 0;
        
        if (self.updateFansListCount) {            
            if (self.dataArray.count > 0) {
                MineFollowItemModel *item = [self.dataArray firstObject];
                self.updateFansListCount(item.followCount);
            }else{
                self.updateFansListCount(@0);
            }

        }
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        [self.tableView reloadData];
        
    } failure:^(id error) {
        self.page--;
        [self stopRefreshing];
    }];
}

- (void)stopRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark - UITableViewDataSource
-  (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MineFollowListCell *cell = [MineFollowListCell cellWithTableView:tableView];
    cell.model = self.dataArray[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

#pragma mark - MineFollowListCellDelegate
- (void)showUserInfoListAtCurrentModel:(MineFollowItemModel *)itemModel{
   
    if (itemModel.isDeleted.intValue == 1) {
        [WHToast showMessage:@"该用户已注销" duration:2 finishHandler:nil];
        return;
    }
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":itemModel.userId,@"loadType":@(1)} completion:nil];
}
- (void)followAtCurrentModel:(MineFollowItemModel *)itemModel{
   
    [SVProgressHUD show];
    BOOL status = NO;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"followId"] = itemModel.userId;
    param[@"md5"] = [RPAppManager md5StrWithApi:FollowAndUnFollow];
    /// 未关注
    if (itemModel.followCode.intValue == 0 || itemModel.followCode.intValue == 2) {
        param[@"type"] = @(1);
        status = YES;
    }
    /// 已关注
    if (itemModel.followCode.intValue == 1 || itemModel.followCode.intValue == 3) {
        param[@"type"] = @(2);
    }
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(FollowAndUnFollow) parames:param success:^(id responseObj) {
        if (status) {
            [WHToast showMessage:@"关注成功" duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"取消关注" duration:2 finishHandler:nil];
        }
   

        NSNumber *followType =  responseObj[RESPONSE][@"followCode"];
        itemModel.followCode = followType;
        NSInteger index = [self.dataArray indexOfObject:itemModel];
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if (self.addOrDeleteFollowListCount) {
            self.addOrDeleteFollowListCount(status,itemModel);
        }
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateUserInfoFollowListStatus" object:nil userInfo:@{@"data":itemModel}];
        
        __block BOOL isLocal = NO;
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            RLMResults<UserInfoFollowModel *> *result = [UserInfoFollowModel allObjects];
            if (result.count > 0) {
                for (int index = 0; index < result.count; index++) {
                    UserInfoFollowModel *resultModel = result[index];
                    if (resultModel.userId == itemModel.userId.longValue) {
                        resultModel.followCode = itemModel.followCode.longValue;
                        isLocal = YES;
                        break;
                    }
                }
            }
            if (!isLocal) {
                UserInfoFollowModel *userInfo = [[UserInfoFollowModel alloc]init];
                userInfo.userId = itemModel.userId.longValue;
                userInfo.followCode = itemModel.followCode.longValue;
                userInfo.realName = itemModel.realName;
                [realm addOrUpdateObject:userInfo];
            }
        }];
        
        //隐藏按钮
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}


@end
